<template>
  <div>
    <div class="search">
      <input type="text" v-model="keywork" placeholder="输入城市名称或拼音" class="search_input"/>
    </div>
    <div class="search_content" ref="search" v-show="keywork.length">
      <ul>
        <li class="search_item border-bottom" v-for="item of list" :key="item.id" @click="handleCity(item.name)">{{item.name}}</li>
        <li class="search_item border-bottom" v-show="showLi">没有匹配到信息</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  data () {
    return {
      keywork: '',
      list: [],
      timer: null
    }
  },
  computed: {
    showLi () {
      return !this.list.length
    }
  },
  props: {
    cities: Object
  },
  methods: {
    handleCity (city) {
      this.$store.dispatch('changeCity', city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  },
  watch: {
    keywork () {
      if (this.timer) {
        clearInterval(this.timer)
      }
      if (!this.keywork) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const elemt = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keywork) > -1 || value.name.indexOf(this.keywork) > -1) {
              elemt.push(value)
            }
          })
        }
        this.list = elemt
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
 @import '~styles/varibles.styl'
 .search
  height .72rem
  background $bgColor
  padding 0 .1rem
  .search_input
    box-sizing border-box
    width 100%
    text-align center
    border-radius .06rem
    height .62rem
    line-height .62rem
    color #666666
    padding 0 .1rem
 .search_content
  position absolute
  top 1.58rem
  left 0
  bottom 0
  right 0
  background #eee
  z-index 1
  overflow hidden
  .search_item
   padding-left .2rem
   line-height .62rem
   color #666
   background #fff
</style>
